<template>
  <div>
    <div v-if="policyName" class="white-name text-base">
      <span>策略名称:{{ policyName }}</span>
      <el-button class="ml-2.5" v-if="deployFlag" @click="deployFn"
      >{{ deployText }}
      </el-button>
    </div>
    <div v-if="!treeStore.isShowStrategyDetail" class="filter-box">
      <el-form class="white-form" label-width="100" inline style="max-width: 1200px">
        <el-form-item label="搜索内容:">
          <el-input v-model="whiteSearch" :style="auditFormLableWidth" placeholder="请输入搜索内容" />
        </el-form-item>
        <el-button class="white-submit" type="primary" @click="whiteSearchSubmit">搜索</el-button>
      </el-form>
    </div>
    <HETTable
        ref="programWhitelistTable"
        :pageSize="10"
        :tableFields="whitelistTableFields"
        :tableData="programWhitelistTableData"
        :enableSearch="false"
        :tableCheckbox="treeStore.isShowStrategyDetail ? false : true"
        :headerOperation="treeStore.isShowStrategyDetail ? [] : headerOperation()"
        :handleSelectionChange="handleSelectionChange"
        :total="whitelistTotal"
        @getTableData="getWhitelist"
    >
    </HETTable>
    <AddDialog
        ref="addDialog"
        :form="form"
        :policyId="policyId"
        @AddhandleDialog="AddhandleDialog"
    ></AddDialog>
    <DirectoryDialog
        ref="whitelistDirRef"
        :dirFlag="dirFlag"
        :rootDirFlag="rootDirFlag"
        :os="treeStore.osType"
        @handleDialogButton="handleDialogButton"
        :multipleChoice="true"
    ></DirectoryDialog>

    <el-dialog
        :model-value="dialogAsync"
        title="白名单追加策略名称"
        width="30%"
        :center="true"
        :close-on-click-modal="false"
        @close="dialogAsync = false"
    >
      <div class="config-body">
        <el-input v-model="strategyName" placeholder="请填写策略名称"></el-input>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleExport">确定</el-button>
          <el-button @click="dialogAsync = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, toRaw, markRaw, watch, onMounted, inject} from "vue";
import HETTable from "~/components/common/HETTable.vue";
import {ElMessage} from "element-plus";
import {
  req_getWhitelistPolicylist,
  req_getWhitelist,
  req_deleteWhitelistFile,
  req_setWhitelistDeploy,
  req_setWhitelistFile,
  req_setPeriphreal,
} from "~/utils/axios/programWhitelist.js";
import {useTreeStore} from "~/utils/pinia/tree.js";
import {useUserStore} from "~/utils/pinia/user.js";
import {Refresh, Delete, Edit, Plus, Download, Upload} from "@element-plus/icons-vue";
import AddDialog from "~/components/StrategyManagement/common/AddDialog.vue";
import DirectoryDialog from "~/components/common/DirectoryDialog.vue";
import {fromJSON} from "postcss";
import {eventBus} from "~/utils/common/eventBus.js";
import {req_exportStrategyToServer} from "~/utils/axios/common.js";

eventBus.on("getStrategyDetail", (detail) => {
  treeStore.openTreeFlag = false;
  programWhitelistTableData.value = detail.data;
  whitelistTotal.value = detail.total;
  treeStore.osType = detail.fromOs;
  // 冗余代码
  if (
      detail.fromOs != "linux" &&
      whitelistTableFields[whitelistTableFields.length - 1].name != "termSpec"
  ) {
    whitelistTableFields.push(
        {name: "filetype", label: "文件类型"},
        {name: "termSpec", label: "文件描述"}
    );
  }
  if (
      detail.fromOs == "linux" &&
      whitelistTableFields[whitelistTableFields.length - 1].name == "termSpec"
  ) {
    whitelistTableFields.splice(
        whitelistTableFields.length - 2,
        whitelistTableFields.length
    );
  }
});
// 修改成功提示
const successElMessage = () => {
  ElMessage({
    message: "修改成功",
    type: "success",
  });
};
/**
 *
 * 父组件接收的参数
 *
 * **/
const props = defineProps({
  rowData: {
    type: Object,
    default: {},
  },
  dialogShow: {
    type: Function,
    default: () => {
    },
  },
  tabData: {
    type: Array,
    default: [],
  },
});
const emit = defineEmits(["reload"]);
/**
 *
 * 树形文件目录组件
 *
 * **/
// 树形文件目录组件 ref
const whitelistDirRef = ref();
// 树形文件目录组件传参 是否只展示目录
const dirFlag = ref(false);
// 树形文件目录组件传参 是否可以选中根目录
const rootDirFlag = ref(true);
// 树形文件目录组件pinia注册
const treeStore = useTreeStore();
let form = reactive({
  policyName: "",
  file: "",
  desc: "",
});
const policyId = ref("");
// 树形文件目录组件点击确认时的方法
const AddhandleDialog = async () => {
  let importParams = {
    deviceId: treeStore.treeDeviceId,
    policyId: getPolicyId(),
    json: [
      {
        filename: form.file[0],
        filemd5: "",
        termSpec: form.desc,
      },
    ],
  };
  await req_setWhitelistFile(importParams).then(
      (res) => {
        if (res.data.succeed) {
          successElMessage();
        } else {
          ElMessage.error("文件错误");
        }
      },
      (err) => {
        ElMessage.error(err);
      }
  );
  programWhitelistTable.value.getTableData();
};
/**
 *
 * 添加文件模态框
 *
 * ***/
// 模态框的 ref
const addDialog = ref();
// 模态框确认时的回调函数
const handleDialogButton = async (ref, path) => {
  form.file = path;
  if (!dirFlag.value) {
    return;
  }
  let params = {
    deviceId: treeStore.treeDeviceId,
    json: {
      policyId: getPolicyId(),
      path: path,
      usb: 2,
      net: 2,
    },
  };
  req_setPeriphreal(params).then(
      (res) => {
        if (res.data.succeed) {
          successElMessage();
        } else {
          ElMessage.error("文件错误");
        }
      },
      (err) => {
        ElMessage.error(err);
      }
  );
};
/**
 *
 * 表格组件
 *
 * **/
// 表格ref
const programWhitelistTable = ref();
// 表格的data数据存储变量
const programWhitelistTableData = ref();
// 表格的total
const whitelistTotal = ref(0);
// 表格选中复选框时 展示或隐藏删除按钮的标识
let handleSelectionChangeFlag = ref(true);
// 选中的行的数据
const selectionChangeValue = ref(null);
// 已部署的策略
const strategy = ref();
// 白名单列表中点击详情跳转过来时，部署按钮是否展示
const deployFlag = ref(false);
// 部署按钮中的文字
const deployText = ref("部署");
// 已部署策略名称
const policyName = ref();
// 当前程序白名单列表日志表格 列名与数据源设置
const whitelistTableFields = reactive([
  {name: "filename", label: "文件名称"},
  {name: "filepath", label: "路径"},
  {name: "filemd5", label: "指纹特征"},
  {name: "filesize", label: "文件大小"},
  {name: "filetype", label: "文件类型"},
  {name: "termSpec", label: "文件描述"},
]);
// 表格中用户选择复选框时的函数
const handleSelectionChange = (val) => {
  selectionChangeValue.value = val;
  if (val.length >= 1) {
    handleSelectionChangeFlag.value = false;
  } else {
    handleSelectionChangeFlag.value = true;
  }
};
// 表格左上角，则点击部署的方法
const deployFn = async () => {
  if (!treeStore.treeDeviceId || deployText.value == "已部署") {
    return;
  }
  let thisPolicyId = null;
  if (props.rowData && props.rowData.policyId) {
    thisPolicyId = props.rowData.policyId;
  }
  let deployParam = {
    deviceId: treeStore.treeDeviceId,
    policyId: thisPolicyId || strategy.value.policyList[0].policyId,
  };
  await req_setWhitelistDeploy(deployParam).then(
      (res) => {
        successElMessage();
        deployText.value = "已部署";
        props.dialogShow();
        treeStore.treeLinkedTableRef.getTableData();
      },
      (err) => {
        ElMessage.error(err);
      }
  );
  programWhitelistTable.value.getTableData();
};
const getPolicyId = () => {
  if (props.rowData && props.rowData.policyId) {
    return props.rowData.policyId;
  } else if (strategy && strategy.value.policyList.length > 0) {
    return strategy.value.policyList[0].policyId;
  } else {
    return null;
  }
};

// 删除的方法
const delWhitelist = async () => {
  let specwtoidArr = [];
  selectionChangeValue.value.map((item) => {
    specwtoidArr.push(item.specwtoid);
  });
  let deleteParams = {
    deviceId: treeStore.treeDeviceId,
    policyId: getPolicyId(),
    json: specwtoidArr,
  };
  await req_deleteWhitelistFile(deleteParams).then(
      (res) => {
        successElMessage();
      },
      (err) => {
        ElMessage.error(err);
      }
  );
  programWhitelistTable.value.getTableData();
};
const whiteSearchSubmit = () => {
  programWhitelistTable.value.getTableData();
}
const dialogAsync = ref(false);
const strategyName = ref("");
const exportAddWhitelist = () => {
  dialogAsync.value = true;
};
const addDirWhitelist = () => {
  treeStore.directoryDialogVModel = true;
  dirFlag.value = true;
};
const addFileWhitelist = () => {
  addDialog.value.dialogVisibleFn(true);
  dirFlag.value = false;
};

// 表格右上角的按钮
const headerOperation = () => {
  let operationArr = [
    {
      name: "上传追加策略",
      ev: exportAddWhitelist,
      icon: Upload,
      disabled: handleSelectionChangeFlag,
    }
  ]
  if(treeStore.osType == "win" || props.rowData.WhitelistWindows){
    operationArr.unshift({name: "删除", ev: delWhitelist, icon: Delete, disabled: handleSelectionChangeFlag},
    {name: "添加目录", ev: addDirWhitelist, icon: Plus},
    {name: "添加文件", ev: addFileWhitelist, icon: Plus},)
  }
  return operationArr;
};
const whiteSearch = ref('')
// 表格获取数据的接口
const getWhitelist = async (countParams, searchParams, tableSearch, isSearch) => {
  if (treeStore.treeDeviceId) {
    // whitelistAddFlag.value = false;
    let querywhitelistStatus = {
      page: searchParams.$page || 0,
      size: searchParams.$limit || 10,
      status: 1,
    };

    policyName.value = "";
    let thisPolicyId = null;
    if (props.rowData && props.rowData.policyId) {
      thisPolicyId = props.rowData.policyId;
      policyName.value = props.rowData.policyName;
      form.policyName = props.rowData.policyName;
      if (props.rowData.status == 0) {
        deployFlag.value = true;
      }
    } else {
      await req_getWhitelistPolicylist(treeStore.treeDeviceId, querywhitelistStatus).then(
          (res) => {
            strategy.value = res.data;
            if (res.data.policyList && res.data.policyList[0]) {
              policyName.value = res.data.policyList[0].policyName;
              deployFlag.value = false;
              form.policyName = res.data.policyList[0].policyName;
              policyId.value = strategy.value.policyList[0].policyId;
            }
          }
      );
    }

    if (treeStore.osType == "linux") {
      policyId.value = 0;
    }

    let whitelistParams = isSearch ? {
      page: searchParams.$page,
      size: searchParams.$limit,
      type: 1
    } : {
      page: searchParams.$page,
      size: searchParams.$limit,
      type: 1,
      policyId: thisPolicyId || policyId.value,
      key: whiteSearch.value,
    };
    req_getWhitelist(treeStore.treeDeviceId, whitelistParams).then(
        (res) => {
          programWhitelistTableData.value = res.data.whiteList;
          if (
              res.data.osType == "linux" &&
              whitelistTableFields[whitelistTableFields.length - 1].name == "termSpec"
          ) {
            whitelistTableFields.splice(
                whitelistTableFields.length - 2,
                whitelistTableFields.length
            );
            props.tabData.map((item, index) => {
              if (item.label == "例外程序" || item.label == "防护设置") {
                if (item.hide == false) {
                  item.hide = true;
                  if (index == props.tabData.length - 1) {
                    emit("reload");
                  }
                }
              }
              if (item.label == "防杀设置") {
                if (item.hide == true) {
                  item.hide = false;
                  if (index == props.tabData.length - 1) {
                    emit("reload");
                  }
                }
              }
            });
          }
          if (
              res.data.osType != "linux" &&
              whitelistTableFields[whitelistTableFields.length - 1].name != "termSpec"
          ) {
            whitelistTableFields.push(
                {name: "filetype", label: "文件类型"},
                {name: "termSpec", label: "文件描述"}
            );
            props.tabData.map((item, index) => {
              if (item.label == "例外程序" || item.label == "防护设置") {
                if (item.hide == true) {
                  item.hide = false;
                  if (index == props.tabData.length - 1) {
                    emit("reload");
                  }
                }
              }
              if (item.label == "防杀设置") {
                if (item.hide == false) {
                  item.hide = true;
                  if (index == props.tabData.length - 1) {
                    emit("reload");
                  }
                }
              }
            });
          }
          whitelistTotal.value = Number(res.data.total) || 0;
        },
        (err) => {
          ElMessage.error(err);
        }
    );
  } else {
    programWhitelistTableData.value = [];
  }
  programWhitelistTable.value.finish();
  // 表格 ref 存入 pinia
  if (!props.rowData.policyId) {
    treeStore.treeLinkedTableRef = programWhitelistTable;
  }
};
const handleExport = () => {
  if (strategyName.value == "") {
    const handleExport = () => {
      if (strategyName.value == "") {
        ElMessage.warning("策略名称不能为空");
        return;
      }
      let params = {
        type: treeStore.treeStrategyType,
        strategyName: strategyName.value,
      };
      req_exportStrategyToServer(treeStore.treeDeviceId, params).then((res) => {
        res.data.succeed ? ElMessage.success("导出成功") : ElMessage.error("导出失败");
        dialogAsync.value = false;
      });
    };
    ElMessage.warning("策略名称不能为空");
    return;
  }
  let params = {
    type: "EXPORT_WHITELIST_ADD",
    strategyName: strategyName.value,
    data: selectionChangeValue.value,
  };
  req_exportStrategyToServer(treeStore.treeDeviceId, params).then((res) => {
    res.data.succeed ? ElMessage.success("导出成功") : ElMessage.error("导出失败");
    dialogAsync.value = false;
  });
};
</script>

<style lang="scss" scoped>
.color {
  color: #333;
}
.white-form{
  :deep(.el-form-item){
    margin-bottom: 0 !important;
  }
}
.filter-box{
  position: relative;
  margin: 0 0 16px 0;
  padding: 10px 24px 10px 0;
  background-color: #fff;
  border-radius: 6px;
}
.white-info-dialog{
  .filter-box{
    position: relative;
    margin: 0 0 16px 0;
    padding: 10px 24px 10px 0;
    background-color: #f4f5f9;
    border-radius: 6px;
  }
}
.white-submit{
  position: absolute;
  right: 24px;
  top: 10px;
}
.white-name{
  position: absolute;
  top: 134px;
  left: 16px;
}
</style>
